<?php

namespace addons\wwh\controller;

use think\Db;
use think\Request;

class Search extends Base
{
    public function index()
    {
        // 获取请求参数
        $keywords = input('keywords', '');
        $type = input('type', '');

        // 分配基础变量到模板
        $this->assign([
            'keywords' => $keywords,
            'type' => $type
        ]);

        // 类型映射
        $typeArr = [
            1 => 'product',
            2 => 'cases',
            3 => 'news'
        ];
        $currentType = $typeArr[$type] ?? '';

        // 获取分页列表数据
        $query = Db::name('wwh_archives')
            ->where([
                'status' => '1',
                'lang' => $this->lang
            ]);

        if ($currentType) {
            $query->where('type', $currentType);
        }

        if ($keywords) {
            $query->where('title', 'like', "%{$keywords}%");
        }

        $list = $query->paginate(9, false, ['query' => request()->param()]);

        // 获取各类别统计数
        $countQuery = Db::name('wwh_archives')
            ->where([
                'status' => '1',
                'lang' => $this->lang
            ]);

        if ($keywords) {
            $countQuery->where('title', 'like', "%{$keywords}%");
        }

        $result = $countQuery
            ->field(['type', 'COUNT(*) AS total'])
            ->group('type')
            ->select();

        // 初始化统计数组
        $countData = array_fill_keys(['product', 'cases', 'news'], 0);

        // 填充统计结果
        foreach ($result as $item) {
            if (isset($countData[$item['type']])) {
                $countData[$item['type']] = $item['total'];
            }
        }

        // 确定当前导航栏目
        $navCur = ['classify' => $currentType ?: 'none'];

        // 分配变量到模板
        $this->assign([
            'list' => $list,
            'searchPage' => $list->render(),
            'productCount' => $countData['product'],
            'casesCount' => $countData['cases'],
            'newsCount' => $countData['news'],
            'navCur' => $navCur
        ]);

        // AJAX请求返回JSON
        if (Request::instance()->isAjax()) {
            return json([
                'list' => $list,
                'searchPage' => $list->render()
            ]);
        }

        return $this->view->fetch('/search');
    }
}
